package com.sgb.kjwl.utils;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;

/**
 * @ProjectName :实体转换(字段名个别不同也不会有问题)
 * @Author : XiongLi
 * @Time :
 */
public class EntityConversion {
    public static String TAG="EntityConversion";
    public static <B> B modelA2B(Object modelA, Class<B> modelB) {
        try {
            Gson gson = new Gson();
            String gsonA = gson.toJson(modelA);
            B instanceB = gson.fromJson(gsonA, modelB);
            return instanceB;
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * json字符串arraylist
     */
    public static <T> ArrayList jsonToArrayList(String json, Class<T> tClass){
        Type type = new TypeToken<ArrayList<JsonObject>>(){
        }.getType();
        ArrayList<JsonObject> jsonObjects = new Gson().fromJson(json,type);
        ArrayList<T> arrayList = new ArrayList<>();
        for (JsonObject jsonObject:jsonObjects){
            arrayList.add(new Gson().fromJson(jsonObject,tClass));
        }
        return arrayList;
    }
}
